import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { DateAdapter } from '@angular/material/core';
import { TranslateService } from '@ngx-translate/core';
import { RestService } from '../../services/rest.service';
import { SexEnums } from '../../models/wdl-types';

import * as _ from 'lodash';

@Component({
  selector: 'app-pcontact-dialog',
  templateUrl: './pcontact-dialog.component.html',
  styleUrls: ['./pcontact-dialog.component.css']
})
export class PcontactDialogComponent implements OnInit {
  contactForm: FormGroup;
  person: any;
  readonly = false;

  constructor(@Inject(MAT_DIALOG_DATA) private dialogData: any,
              public dialogRef: MatDialogRef<PcontactDialogComponent>,
              private adapter: DateAdapter<any>,
              fb: FormBuilder,
              private rest: RestService,
              private translate: TranslateService,
              private dialog: MatDialog) {
    this.person = dialogData.person;

    this.contactForm = fb.group({
      contact1Name: [
        { value: this.person.contact1Name, disabled: this.readonly },
        [ Validators.maxLength(40) ]
      ],
      contact1Sex: [
        { value: this.getSexFromEnum(this.person.contact1Sex), disabled: this.readonly },
        []
      ],
      contact1Phone: [
        { value: this.person.contact1Phone, disabled: this.readonly },
        [ Validators.maxLength(12) ]
      ],
      contact1Address: [
        { value: this.person.contact1Address, disabled: this.readonly },
        [ Validators.maxLength(128) ]
      ],
      contact2Name: [
        { value: this.person.contact2Name, disabled: this.readonly },
        [ Validators.maxLength(40) ]
      ],
      contact2Sex: [
        { value: this.getSexFromEnum(this.person.contact2Sex), disabled: this.readonly },
        [ ]
      ],
      contact2Phone: [
        { value: this.person.contact2Phone, disabled: this.readonly },
        [ Validators.maxLength(12) ]
      ],
      contact2Address: [
        { value: this.person.contact2Address, disabled: this.readonly },
        [ Validators.maxLength(128) ]
      ],
    });
  }

  getSexFromEnum(input) {
    return input === 'MALE' ? 'male' : 'female';
  }

  submit() {
    const data = {};
    _.forEach(this.contactForm.value, (value, key) => {
      if (key.endsWith('Sex')) {
        data[key] = value === 'male' ? SexEnums.MALE : SexEnums.FEMAIL;
      } else {
        data[key] = _.trim(value);
      }
    });

    this.dialogRef.close(data);
  }

  ngOnInit() {
  }
}